import { getAgreementInfo, ifPopup } from '@/api/app'
import { getStorageCache, removeStorageCache, setStorageCache } from '@/common/cache'
import { isEmpty } from '@/common/helper/is'
import $platform from '@/common/platform'
import ManifestJson from '@/manifest.json'
/**
 * 系统全局APP数据存储
 */

//设置默认State
const getDefaultState = () => {
  return {
    networkStatus: true, // 网络状态
    appInfo: {
      // 应用信息 // app默认信息
      domain: '',
      name: ManifestJson.name, // 应用名称
      logo: CDN('/common/static/images/logo.png'), // logo
      version: ManifestJson.versionName, // 版本号
    },
    platform: {
      payment: [], // 支持的支付方式 ["money", "alipay", "wechat", "offline"]
      recharge_payment: [], // 支持的充值支付方式  ["wechat", "alipay"]
      share: {
        methods: ['forward', 'poster', 'link', 'image'], // 支持的分享方式
        forwardInfo: {
          // 链接分享信息
          title: ManifestJson.name, // 标题
          desc: '苏享家公寓', // 介绍
          image: CDN('/common/static/images/share/share_200x160.png'), // 分享图
        }, // 默认转发信息
        posterInfo: {
          // 海报分享信息
          type: 'poster', // 分享海报 默认此处类型 关联海报组件cu-poster中components引用那种类型的海报展示方式，可自行扩充
          title: '', // 标题
          image: CDN('/common/static/images/share/poster_646x948.png'),
          user_bg: '',
        }, // 海报信息
        linkAddress: '', // 复制链接地址location.origin
      },
      autoLogin: 1, // 自动登陆
      bindMobile: 0, // 登陆后绑定手机号提醒 (弱提醒，可手动关闭)
    },
    appLaunchScene: 1001, // 小程序进入场景
    camera: {
      uploadUrl: '', // 照相机图片上传地址
    },
    // 自定义底部菜单栏配置
    tabbarConfig: {
      basic: {
        activeColor: '#046f7e',
        inactiveColor: '#7d7e80',
      },
      list: [
        {
          path: '/pages/main/home',
          inactiveIcon: CDN('/common/static/images/tabBar/home.png'),
          activeIcon: CDN('/common/static/images/tabBar/homeSelected.png'),
          text: '首页',
          dot: false,
          badge: null,
        },
        {
          path: '/pages/main/user',
          inactiveIcon: CDN('/common/static/images/tabBar/user.png'),
          activeIcon: CDN('/common/static/images/tabBar/userSelected.png'),
          text: '我的',
          dot: false,
          badge: null,
        },
      ],
    },

    // 广告
    adInfo: {
      list: [
        { image: 'https://cdn.uviewui.com/uview/swiper/swiper1.png', path: '/user/index' },
        { image: 'https://cdn.uviewui.com/uview/swiper/swiper3.png', path: '/user/index' },
      ],
    },
  }
}
//初始化State
const state = {
  // 隐私协议
  dialogIsAgree: getStorageCache('dialogIsAgree'),
  argeementInfo: {},

  ...getDefaultState(),
  questionInfo: null,
}

const mutations = {
  SET_NETWORKSTATUS: (state, status) => {
    state.networkStatus = status
  },

  SET_APP_INFO: (state, appInfo) => {
    state.appInfo = appInfo
  },

  SET_SHARE_INFO: (state, shareInfo) => {
    state.platform.share = shareInfo
  },

  SET_ISAGREE(state, agree) {
    state.dialogIsAgree = agree
    setStorageCache('dialogIsAgree', agree)
  },

  SET_AGREEMENT_INFO(state, argeementInfo) {
    state.argeementInfo = argeementInfo
  },
  SET_QUESTION_INFO(state, questionInfo) {
    state.questionInfo = questionInfo
  },
  SET_AUTH_PERM_INFO(state, sysAuthPermInfo) {
    state.sysAuthPermInfo = sysAuthPermInfo
  },

  SET_SCENE(state, scene) {
    state.appLaunchScene = scene
  },

  RESET_STATE(state) {
    Object.assign(state, getDefaultState())
    // removeStorageCache('Env-Config')
    // removeStorageCache('dialogIsAgree')
  },
  SET_CAMERA_URL: (state, data) => {
    state.camera.uploadUrl = data
  },
}

const actions = {
  ResetState({ commit }) {
    commit('RESET_STATE')
  },

  // 初始化
  async SetAppInitInfo({ commit, dispatch, rootGetters }, isClear = true) {
    //检查网络
    const networkStatus = await $platform.checkNetwork()
    commit('SET_NETWORKSTATUS', networkStatus)

    // 清除数据环境缓存
    if (isClear) removeStorageCache('Env-Config')

    if (networkStatus) {
      const { query, scene } = uni.getEnterOptionsSync()
      commit('SET_SCENE', scene)

      // start 外部应用携带token链接 进入免登录
      const token = query?.token
      // 且当前应用没有登录的情况下注入来源的token
      if (token && !rootGetters.token) commit('user/SET_TOKEN', token, { root: true })
      // end

      if (![1154].includes(scene)) $platform.load()
      // 隐私协议
      dispatch('GetAgreementInfo')
      // 获取定位
      // if (!rootGetters.locationInfo.longitude) dispatch('location/GetLocation', {}, { root: true })
      dispatch('location/SetCurDefaultCity', {}, { root: true })

      // 获取用户信息
      if (rootGetters.isLogin && isEmpty(rootGetters.userInfo)) await dispatch('user/GetUserInfo', {}, { root: true })

      if (rootGetters.isLogin) dispatch('getIfQuestionPopup')
    }
  },

  // 隐私协议
  async GetAgreementInfo({ commit }) {
    const { errcode, data } = await getAgreementInfo()
    if (errcode === 0) {
      commit('SET_AGREEMENT_INFO', data)
    }
  },

  //是否弹出问卷弹框
  async getIfQuestionPopup({ commit, rootGetters }) {
    const data = await ifPopup({ user_id: rootGetters.userInfo.user_id || '', mac: $platform.device.deviceId })
    // const data = await ifPopup({ user_id: '', mac: $platform.device.deviceId })
    if (data.errcode == 0 && data.data) {
      commit('SET_QUESTION_INFO', data.data)
    }
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
